package com.seafwg.store.service.impl;

import com.seafwg.store.entity.Address;
import com.seafwg.store.mapper.AddressMapper;
import com.seafwg.store.mapper.DistrictMapper;
import com.seafwg.store.service.IAddressService;
import com.seafwg.store.service.ex.AddressCountLimitException;
import com.seafwg.store.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author seafwg
 * @Date 2022/3/25 2:45 下午
 * @Version 1.0
 * @description 用户地址模块业务层的实现层
 */
@Service
public class AddressServiceImpl implements IAddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private DistrictMapper districtMapper;

    // 地址的数量
    @Value("${user.address.MAX_COUNT}")
    private int ADDRESS_MAX_COUNT;

    /**
     * 新增用户地址
     * @param uid 用户uid
     * @param username 用户名
     * @param address 地址对象：地址信息
     */
    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        // 判断该用户的地址是否受限制
        Integer sum = addressMapper.queryAddressSum(uid);
        if(sum > ADDRESS_MAX_COUNT) {
            throw new AddressCountLimitException("收货地址数量已经超过上限["+ADDRESS_MAX_COUNT+"]");
        }
        // 补全字段
        address.setUid(uid);
        Integer isDefault = sum == 0 ? 1 : 0; // 总数为0则是第一个，设置为默认
        address.setIsDefault(isDefault);
        // 四项基本信息
        address.setCreatedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedUser(username);
        address.setModifiedTime(new Date());

        // 根据code值获取到对应的名称填充
        String provinceName = districtMapper.findDistrictNameByCode(address.getProvinceCode());
        String cityName = districtMapper.findDistrictNameByCode(address.getCityCode());
        String areaName = districtMapper.findDistrictNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);

        // 添加收货地址信息
        Integer rows = addressMapper.insertAddress(address);
        if (rows != 1) {
            throw new InsertException("插入数据库时发生异常信息，请联系管理员");
        }
    }
}
